import Vue from 'vue'
import Router from 'vue-router'
import NPrg from 'nprogress'
import 'nprogress/nprogress.css'

import vuecfg from '@/../vue.config'
import utils from '@/utils'
import store from '@/store'
import { routes/*, dynamicRoutes*/ } from './routes'

Vue.use(Router)

const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes
})

export function resetRouter() {
  const newRouter = createRouter()
  // Refer: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
  router.matcher = newRouter.matcher
}

const router = createRouter()
export default router

var getPageTitle = title =>
  (title ? (title + '_') : '') + (vuecfg.configureWebpack.name || 'Vue Template')

const loginPage = '/login'
const noRedirect = [loginPage] // free login white list
router.beforeEach(async(to, from, next) => {
  NPrg.start()
  document.title = getPageTitle(to.meta.title)

  const loginRedirect = loginPage + `?redirect=${to.path}`
  let redirectPath
  if (!utils.cookie.getToken()) {
    if (noRedirect.indexOf(to.path) === -1) { // has no token!
      redirectPath = loginRedirect
    }
  } else if (to.path === loginPage) { // already logged in, redirect to home page
    redirectPath = '/'
  } else if (!store.state.user.roles || store.state.user.roles.length === 0) {
    try { // get user info
      await store.dispatch('user/getUserInfo')
    } catch (err) { // remove token and re-login
      console.warn('Get user info failed:', err)
      await store.dispatch('user/resetToken')
      redirectPath = loginRedirect
    }
  }
  if (redirectPath) {
    next(redirectPath)
    NPrg.done()
  } else {
    next()
  }
})

router.afterEach(() => {
  NPrg.done()
})

